<template>
  <a-layout class="admin-layout">
    <!-- 侧边栏 -->
    <a-layout-sider
      v-model:collapsed="collapsed"
      :trigger="null"
      collapsible
      class="admin-sider"
      :width="256"
    >
      <div class="logo">
        <h2>智教后台管理</h2>
      </div>
      <div class="menu-container">
        <a-menu
          v-model:selectedKeys="selectedKeys"
          theme="dark"
          mode="inline"
          @click="handleMenuClick"
          class="admin-menu"
        >
          <template v-for="item in menuItems" :key="item.key">
            <!-- 如果有子菜单，使用 a-sub-menu -->
            <a-sub-menu v-if="item.children && item.children.length > 0" :key="item.key">
              <template #title>
                <span>{{ item.name }}</span>
              </template>
              <!-- 渲染子菜单 -->
              <a-menu-item v-for="child in item.children" :key="`${item.key}-${child.id}`">
                <span>{{ child.name }}</span>
              </a-menu-item>
            </a-sub-menu>
            <!-- 如果没有子菜单，使用普通的 a-menu-item -->
            <a-menu-item v-else-if="!item.children || item.children.length === 0" :key="item.key">
              <span>{{ item.name }}</span>
            </a-menu-item>
          </template>
        </a-menu>
      </div>
    </a-layout-sider>

        <!-- 主布局 -->
        <a-layout class="main-layout">
            <!-- 顶部导航 -->
            <a-layout-header class="admin-header">
                <div class="header-left">
                    <a-button type="text" @click="collapsed = !collapsed" class="collapse-btn">
                        <MenuUnfoldOutlined v-if="collapsed" />
                        <MenuFoldOutlined v-else />
                    </a-button>
                    <a-breadcrumb class="breadcrumb">
                        <a-breadcrumb-item>管理后台</a-breadcrumb-item>
                        <a-breadcrumb-item>{{ currentPageTitle }}</a-breadcrumb-item>
                    </a-breadcrumb>
                </div>
                <div class="header-right">
                    <a-dropdown>
                        <a-button type="text" class="user-dropdown">
                            <UserOutlined />
                            管理员
                            <DownOutlined />
                        </a-button>
                        <template #overlay>
                            <a-menu>
                                <a-menu-item @click="handleLogout">
                                    <LogoutOutlined />
                                    退出登录
                                </a-menu-item>
                            </a-menu>
                        </template>
                    </a-dropdown>
                </div>
            </a-layout-header>

      <!-- 主内容区域 -->
      <a-layout-content class="admin-content">
        <div class="content-wrapper">
          <router-view />
        </div>
      </a-layout-content>
    </a-layout>
  </a-layout>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { useAuthStore } from '@/stores/authStore'
import { getUserMenu } from '@/api/user/sysPermissionController'
import {
  DashboardOutlined,
  BookOutlined,
  UserOutlined,
  FileTextOutlined,
  FormOutlined,
  ShoppingOutlined,
  SettingOutlined,
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  DownOutlined,
  LogoutOutlined,
} from '@ant-design/icons-vue'
import { initWebSocket } from '@/utils/websocketManager'
import { logout as authLogout } from '@/api/user/authController'

// 初始化WebSocket连接
initWebSocket()

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

// 响应式数据
const collapsed = ref(false)
const selectedKeys = ref(['dashboard'])
const menuItems = ref([])

// 响应式处理
const handleResize = () => {
  if (window.innerWidth <= 768) {
    collapsed.value = true
  }
}

// 计算属性
const currentPageTitle = computed(() => {
  const pageTitles = {
    adminDashboard: '数据概览',
    adminUsers: '用户管理',
    adminRoles: '角色管理',
    adminPermissions: '权限管理',
    adminMenus: '菜单管理',
    adminCourses: '课程管理',
    adminInstitutions: '机构管理',
    adminOrders: '订单管理',
    adminAssignments: '作业管理',
    adminExams: '考试管理',
    adminSettings: '系统设置',
    adminDepts: '部门管理',
        'adminProducts': '商品管理',
        'adminData': '数据概览',
        
    adminWorksReview: '作品审核',
  }
  return pageTitles[String(route.name)] || '管理后台'
})

// 方法
const handleMenuClick = ({ key }) => {
    selectedKeys.value = [key]
    
    // 处理子菜单点击
    if (key.includes('-')) {
        // 子菜单点击，格式：parentKey-childId
        const [parentKey, childId] = key.split('-')
        console.log('子菜单点击:', parentKey, childId)
        
        // 查找对应的子菜单项以获取URL
        let targetUrl = null;
        for (const item of menuItems.value) {
            if (item.key === parentKey && item.children) {
                const child = item.children.find(c => `${item.key}-${c.id}` === key);
                if (child && child.url) {
                    targetUrl = child.url;
                    console.log('找到子菜单URL:', targetUrl)
                    break;
                }
            }
        }
        
        if (targetUrl) {
            router.push(`/admin${targetUrl}`);
        } else {
            // 默认跳转逻辑
            switch (parentKey) {
                case 'user':
                    router.push('/admin/users')
                    break
                case 'role':
                    router.push('/admin/roles')
                    break
                case 'permission':
                    router.push('/admin/permissions')
                    break
                case 'menu':
                    router.push('/admin/menus')
                    break
                case 'class':
                    router.push('/admin/courses')
                    break
                case 'dept':
                    router.push('/admin/depts')
                case 'products':
                    router.push('/admin/products')
                    break
                default:
                    console.log('未知的子菜单:', parentKey)
            }
        }
        return
    }
    
    // 父菜单点击
    // 查找对应的父菜单项以获取URL
    let targetUrl = null;
    const menuItem = menuItems.value.find(item => item.key === key);
    if (menuItem && menuItem.url) {
        targetUrl = menuItem.url;
        console.log('找到父菜单URL:', targetUrl)
    }
    
    if (targetUrl) {
        // 特殊处理数据概览路由
        if (targetUrl === '/AllData') {
            router.push('/admin/AllData');
        } else {
            router.push(`/admin${targetUrl}`);
        }
    } else {
        // 默认跳转逻辑
        switch (key) {
            case 'dashboard':
                router.push('/admin')
                break
            case 'user':
                router.push('/admin/users')
                break
            case 'role':
                router.push('/admin/roles')
                break
            case 'permission':
                router.push('/admin/permissions')
                break
            case 'menu':
                router.push('/admin/menus')
                break
            case 'class':
                router.push('/admin/courses')
                break
            case 'dept':
                router.push('/admin/depts')
                break
            case 'data':
                router.push('/admin/AllData')
                break
            default:
                router.push('/admin')
        }
    }
}

const handleLogout = async () => {
    try {
        // 调用API登出
        await authLogout()
        // 清除本地认证信息
      authStore.logout()
        // 跳转到登录页
        router.push('/login')
    } catch (error) {
        console.error('登出失败:', error)
        message.error('登出失败')
    }
}

// 根据当前路由设置选中的菜单项
const updateSelectedKeys = () => {
  const path = route.path
  if (path === '/admin') {
    selectedKeys.value = ['dashboard']
  } else if (path === '/admin/AllData') {
    selectedKeys.value = ['data']
  } else {
    // 从路径中提取关键部分进行匹配
    const parts = path.split('/').filter((part) => part)
    if (parts.length >= 2) {
      const key = parts[1]
      if (key) {
        // 特殊处理一些路由映射
        const keyMap = {
          users: 'user',
          roles: 'role',
          permissions: 'permission',
          depts: 'dept',
          AllData: 'data',
        }
        selectedKeys.value = [keyMap[key] || key]
      }
    }
  }
}

// 监听路由变化
watch(
  () => route.path,
  () => {
    updateSelectedKeys()
  },
  { immediate: true },
)

// 监听窗口大小变化
onMounted(async () => {
  handleResize()
  window.addEventListener('resize', handleResize)

    // 拉取权限菜单（包含子菜单）
    try {
        const res = await getUserMenu()
        const resAny = res
        if (resAny && resAny.code === '00000' && Array.isArray(resAny.data)) {
            const roots = resAny.data.filter((i) => i.type === 1)
            menuItems.value = roots
                .sort((a, b) => (a.sort || 0) - (b.sort || 0))
                .map(i => ({
                    key: normalizeKey(i.url),
                    name: i.name,
                    url: i.url,
                    children: (i.children || []).filter(child => child.type === 1) // 只保留type=1的子菜单
                        .map(child => ({
                            ...child,
                            key: normalizeKey(child.url)
                        }))
                }))
            
            // 如果菜单中没有商品管理，手动添加
            const hasProductMenu = menuItems.value.some(item => item.key === 'products')
            if (!hasProductMenu) {
                menuItems.value.push({
                    key: 'products',
                    name: '商品管理',
                    url: '/products',
                    children: []
                })
            }
        }
    } catch (e) {
        console.error('获取用户菜单失败', e)
        message.error('获取菜单失败')
        
        // 如果API调用失败，使用空菜单
        menuItems.value = []
    }
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

function normalizeKey(url) {
  if (!url) return 'dashboard'

  // 根据后端返回的url映射到正确的key
  const urlMap = {
    '/user': 'user',
    '/roles': 'role',
    '/permission': 'permission',
    '/dept': 'dept',
    '/data': 'data',
    '/AllData': 'data',
  }

  const key = urlMap[url] || String(url).replace(/^\//, '')
  console.log('normalizeKey', url, key)
  return key || 'dashboard'
}
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  overflow: hidden;
}

/* 侧边栏样式 */
.admin-sider {
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  z-index: 1000;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
  transition: all 0.2s ease;
}

.logo {
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid #001529;
  background: #001529;
}

.logo h2 {
  color: #fff;
  margin: 0;
  font-size: 18px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.menu-container {
  height: calc(100vh - 64px);
  overflow-y: auto;
  overflow-x: hidden;
}

.admin-menu {
  border-right: none;
  height: 100%;
}

/* 主布局样式 */
.main-layout {
  margin-left: 256px;
  transition: margin-left 0.2s ease;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 侧边栏收起时的主布局 */
.admin-layout.ant-layout-sider-collapsed .main-layout {
  margin-left: 80px;
}

/* 顶部导航样式 */
.admin-header {
  position: fixed;
  top: 0;
  right: 0;
  left: 256px;
  z-index: 999;
  background: #fff;
  padding: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: left 0.2s ease;
  height: 64px;
}

/* 侧边栏收起时的顶部导航 */
.admin-layout.ant-layout-sider-collapsed .admin-header {
  left: 80px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
  padding-left: 16px;
}

.collapse-btn {
  font-size: 16px;
  width: 64px;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background: transparent;
  transition: all 0.3s ease;
}

.collapse-btn:hover {
  background: #f5f5f5;
  color: #1890ff;
}

.breadcrumb {
  font-size: 14px;
}

.header-right {
  padding-right: 24px;
}

.user-dropdown {
  height: 64px;
  display: flex;
  align-items: center;
  padding: 0 16px;
  border: none;
  background: transparent;
  transition: all 0.3s ease;
}

.user-dropdown:hover {
  background: #f5f5f5;
  color: #1890ff;
}

/* 主内容区域样式 */
.admin-content {
  margin-top: 64px;
  height: calc(100vh - 64px);
  overflow: hidden;
  background: #f0f2f5;
  padding: 0;
}

.content-wrapper {
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 24px;
}

/* 滚动条样式 */
.menu-container::-webkit-scrollbar,
.content-wrapper::-webkit-scrollbar {
  width: 6px;
}

.menu-container::-webkit-scrollbar-track,
.content-wrapper::-webkit-scrollbar-track {
  background: transparent;
}

.menu-container::-webkit-scrollbar-thumb,
.content-wrapper::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

.menu-container::-webkit-scrollbar-thumb:hover,
.content-wrapper::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .admin-sider {
    transform: translateX(-100%);
  }

  .admin-sider.ant-layout-sider-collapsed {
    transform: translateX(0);
  }

  .main-layout {
    margin-left: 0;
  }

  .admin-header {
    left: 0;
  }
}

/* 菜单项悬停效果 */
.admin-menu .ant-menu-item {
  transition: all 0.3s ease;
}

.admin-menu .ant-menu-item:hover {
  background: rgba(255, 255, 255, 0.1);
  transform: translateX(4px);
}

.admin-menu .ant-menu-item-selected {
  background: #1890ff !important;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

/* 内容区域卡片样式 */
.content-wrapper :deep(.ant-card) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  margin-bottom: 24px;
}

.content-wrapper :deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

/* 表格样式优化 */
.content-wrapper :deep(.ant-table) {
  border-radius: 8px;
  overflow: hidden;
}

.content-wrapper :deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}

/* 按钮样式优化 */
.content-wrapper :deep(.ant-btn) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.content-wrapper :deep(.ant-btn:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 表单样式优化 */
.content-wrapper :deep(.ant-form-item-label > label) {
  font-weight: 500;
  color: #333;
}

.content-wrapper :deep(.ant-input),
.content-wrapper :deep(.ant-select-selector) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.content-wrapper :deep(.ant-input:focus),
.content-wrapper :deep(.ant-select-focused .ant-select-selector) {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}
</style>
